package com.sjsu.CMPE226.shard.hibernate.app;

import java.util.Date;
import java.text.SimpleDateFormat;

import com.sjsu.CMPE226.shard.hibernate.util.HibernateUtil;
import com.sjsu.CMPE226.shard.hibernate.util.HibernateUtil.Shard;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class LocationHash {
	private int numNodes;

	public LocationHash(int numNodes) {
		this.numNodes = numNodes;
	}

	protected int locateServerNum(Date observationsDateTime) {
		int serverNum = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = sdf.parse("2012-10-04");
			if (observationsDateTime.before(date1)) {
				serverNum = 1;
			} else {
				serverNum = 2;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return serverNum;
	}

	public Session[] allLocations() {
		SessionFactory list[] = HibernateUtil.getLocations();
		Session[] r = new Session[list.length];
		for (int n = 0; n < list.length; n++)
			r[n] = list[n].getCurrentSession();

		return r;
	}

	public Session locate(Date observationsDateTime) {
		Shard shard = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date1 = sdf.parse("2012-10-04");
			if (observationsDateTime.before(date1)) {
				shard = Shard.one;
			}
			else {
				shard = Shard.two;
			}
			System.out.println("----> " + observationsDateTime + " maps to " + shard);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return HibernateUtil.getSessionFactory(shard).getCurrentSession();
	}
}
